package cn.gbase.jiangsu.data.transfer.action;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.annotation.At;
import org.nutz.mvc.annotation.By;
import org.nutz.mvc.annotation.Fail;
import org.nutz.mvc.annotation.Filters;
import org.nutz.mvc.annotation.Ok;
import org.nutz.mvc.annotation.POST;
import org.nutz.mvc.annotation.Param;
import org.nutz.mvc.filter.CheckSession;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.Community;
import cn.gbase.jiangsu.data.transfer.bean.CommunityBuilding;
import cn.gbase.jiangsu.data.transfer.bean.CompanyUser;
import cn.gbase.jiangsu.data.transfer.bean.ForumReply;
import cn.gbase.jiangsu.data.transfer.bean.ForumTopic;
import cn.gbase.jiangsu.data.transfer.bean.ShopUser;
import cn.gbase.jiangsu.data.transfer.service.CompanyService;
import cn.gbase.jiangsu.data.transfer.service.CompanyUserService;
import cn.gbase.jiangsu.data.transfer.service.ForumC2UService;

/**
 * 论坛管理功能（服务站与会员之间）.
 * 
 */
@IocBean(args = { "refer:dao" })
@At("/forumC2U")
@Filters(@By(type = CheckSession.class, args = { "companyUser", "jsp:/companyIndex" }))
public class ForumC2UAction extends IdEntityService<CompanyUser> {

	@Inject
	private ForumC2UService forumC2UService;
	@Inject
	private CompanyService companyService;
	@Inject
	private CompanyUserService companyUserService;

	public ForumC2UAction() {
		super();
	}

	public ForumC2UAction(Dao dao) {
		super(dao);
	}

	/**
	 * 分页查询主题（主题管理页面）.
	 * 
	 * @param currentPage
	 * @param groupId
	 * @param addTime
	 * @param keyword
	 * @param req
	 * @throws UnsupportedEncodingException
	 */
	@At("/listTopic")
	@Ok("jsp:/forumC2U/listTopic")
	public QueryResult listTopic(@Param("p") int currentPage, @Param("supplierId") int supplierId,
			@Param("title") String title, HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");

		// 回传表单输入
		Map<String, String> itemMap = new HashMap<String, String>();
		itemMap.put("supplierId", "" + supplierId);
		itemMap.put("title", title);
		request.setAttribute("formdata", itemMap);
		request.setAttribute("fromId", u.getCompanyId());

		return forumC2UService.getTopicList(currentPage, supplierId, title, u.getCompanyId());
	}

	/**
	 * 跳转到查看主题页面（主题管理）.
	 */
	@At("/viewTopic")
	@Ok("jsp:/forumC2U/viewTopic")
	public void toViewTopic(@Param("topicId") int topicId, HttpServletRequest req) {

		// 主题
		ForumTopic topic = forumC2UService.getTopic(topicId);
		if (topic == null) {
			throw new RuntimeException("该主题不存在。");
		}
		req.setAttribute("topic", topic);

		//查看次数+1
		forumC2UService.updateTopicClick(topicId, topic.getClick() + 1);

		// 取得回复列表
		List<ForumReply> replyList = forumC2UService.getReplyList(topicId);
		req.setAttribute("replyList", replyList);

	}

	/**
	 * 跳转到添加主题页面（主题管理）.
	 */
	@At("/toAddTopic")
	@Ok("jsp:/forumC2U/editTopic")
	public void toAddTopic(HttpServletRequest req, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		List<Community> communityList = companyService.getCommunity(u.getCompanyId());
		List<CommunityBuilding> building = companyService.getBuilding(u.getCompanyId());
		req.setAttribute("communityList", communityList);
		req.setAttribute("buildingList", building);
	}

	/**
	 * 跳转到修改主题页面.
	 */
	@At("/toEditTopic")
	@Ok("jsp:/forumC2U/editTopic")
	public void toEditTopic(@Param("id") int id, HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		// 要修改的主题
		ForumTopic p = forumC2UService.getTopic(id);
		/// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		//小区
		String community = request.getParameter("community");
		//楼号
		String buildNo = request.getParameter("buildNo");
		//单元号
		String unitNo = request.getParameter("unitNo");
		//门牌号
		String roomNo = request.getParameter("roomNo");
		//购买会员号
		String userNo = request.getParameter("userNo");
		if (userNo == null || !(userNo.length() > 0) || "0".equals(userNo))
			userNo = p.getToId().toString();
		if (userNo != null && userNo.length() > 0 && !"0".equals(userNo)) {
			// 取得用户
			ShopUser user = this.dao().fetch(ShopUser.class, Cnd.where("id", "=", userNo));
			//会员名
			String realName = user.getRealName();
			itemMap.put("realName", realName);
		}
		// 回传表单输入
		itemMap.put("community", community);
		itemMap.put("buildNo", buildNo);
		itemMap.put("unitNo", unitNo);
		itemMap.put("userNo", userNo);
		itemMap.put("roomNo", roomNo);
		request.setAttribute("topic", p);
		request.setAttribute("formdata", itemMap);
		List<Community> communityList = companyService.getCommunity(u.getCompanyId());
		List<CommunityBuilding> building = companyService.getBuilding(u.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);

	}

	/**
	 * 跳转到修改主题页面.
	 */
	@At("/toUserTopic")
	@Ok("jsp:/forumC2U/userTopic")
	public void toUserTopic(@Param("id") int id, HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");

		/// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();

		//购买会员号
		String userNo = request.getParameter("userNo");
		if (userNo != null && userNo.length() > 0 && !"0".equals(userNo)) {
			// 取得用户
			ShopUser user = this.dao().fetch(ShopUser.class, Cnd.where("id", "=", userNo));
			//会员名
			String realName = user.getRealName();
			itemMap.put("realName", realName);
		}

		itemMap.put("userNo", userNo);

		request.setAttribute("formdata", itemMap);

	}

	/**
	 * 保存主题.
	 * 
	 * @param sp
	 */
	@At("/saveTopic")
	@POST
	@Ok(">>:/forumC2U/listTopic")
	@Fail("jsp:/forumC2U/editTopic")
	public void saveTopic(@Param("..") ForumTopic Topic, HttpServletRequest request, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		/// 回传数据
		Map<String, String> itemMap = new HashMap<String, String>();
		//小区
		String community = request.getParameter("community");
		//楼号
		String buildNo = request.getParameter("buildNo");
		//单元号
		String unitNo = request.getParameter("unitNo");
		//门牌号
		String roomNo = request.getParameter("roomNo");
		//购买会员号
		String userNo = request.getParameter("userNo");
		//会员名称
		String realName = request.getParameter("realName");
		// 回传表单输入
		itemMap.put("community", community);
		itemMap.put("buildNo", buildNo);
		itemMap.put("unitNo", unitNo);
		itemMap.put("userNo", userNo);
		itemMap.put("roomNo", roomNo);
		itemMap.put("realName", realName);
		request.setAttribute("formdata", itemMap);
		List<Community> communityList = companyService.getCommunity(u.getCompanyId());
		List<CommunityBuilding> building = companyService.getBuilding(u.getCompanyId());
		request.setAttribute("communityList", communityList);
		request.setAttribute("buildingList", building);
		if (userNo != null && userNo.length() > 0)
			Topic.setToId(Integer.valueOf(userNo));
		else
			Topic.setToId(0);
		forumC2UService.addOrUpdTopic(Topic, u.getCompanyId());
	}

	/**
	 * 删除主题（逻辑删除）.
	 */
	@At("/delete")
	@Ok("json")
	public String delete(@Param("id") int id) {
		forumC2UService.deleteTopic(id);
		return "{id:0}";
	}

	/**
	 * 删除主题（逻辑删除）.
	 */
	@At("/deleteMany")
	@Ok("json")
	public String deleteMany(@Param("idStr") String idStr) {
		String[] idArray = idStr.split(",");
		for (String id : idArray) {
			forumC2UService.deleteTopic(Integer.valueOf(id));
		}
		return "{id:0}";
	}

	/**
	 * 保存回复.
	 * 
	 * @param sp
	 */
	@At("/saveReply")
	@POST
	@Ok(">>:/forumC2U/viewTopic?topicId=${obj}")
	public int saveReply(@Param("..") ForumReply reply, HttpSession session) {
		CompanyUser u = (CompanyUser) session.getAttribute("companyUser");
		forumC2UService.addOrUpdateReply(reply, u.getCompanyId());
		return reply.getTopicId();
	}

}
